<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/5/6
 * Time: 22:04
 */

namespace app\admin\model;

use think\Model;
class User extends Model
{
    /**
     * 根据条件获取用户列表信息
     * @param $where
     * @param $offset
     * @param $limit
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getUserByWhere($where, $offset, $limit){
        return $this->where($where)->whereOr('status',1)->limit($offset,$limit)->order('id desc')->select();
    }

    /**
     * 根据搜索条件获取所有的用户数量
     * @param $where
     * @return int|string
     */
    public function getAllUser($where){
        return $this->where($where)->count();
    }

    /**
     * 添加用户数据
     * @param $data
     * @return array|bool
     */
    public function addUser($data){
        if (empty($data) || !is_array($data)) {
            return false;
        }
        try{
            $data['password'] = md5('123456');
            $result = $this->validate('UserValidate')->save($data);
            if ($result === false) {
                return msg(-1,'',$this->getError());
            } else {
                return msg(1,url('User/index'), '添加用户成功！');
            }
        }catch (\PDOException $e) {
            return msg(-2,'',$e->getMessage());
        }
    }

    /**
     * 编辑用户数据
     * @param $data
     * @return array|bool
     */
    public function editUser($data){
        if (empty($data) || !is_array($data)) {
            return false;
        }
        try{
//            $data['password'] = md5('123456');
            $data['birthday'] = strtotime($data['birthday']);
            $result = $this->validate('UserValidate')->save($data,array('id'=>$data['id']));
            if ($result === false) {
                return msg(-1,'',$this->getError());
            } else {
                return msg(1,url('User/index'), '编辑用户成功！');
            }
        }catch (\PDOException $e) {
            return msg(-2,'',$e->getMessage());
        }
    }

    /**
     * 获取单个用户数据
     * @param $id
     * @return array|bool|false|\PDOStatement|string|Model
     */
    public function getOneUser($id) {
        if (empty($id)) {
            return false;
        }
        $res = $this->find($id);
        $res['birthday'] = date('Y-m-d',$res['birthday']);
        return $res;
    }

    /**
     * 删除数据
     * @param $id
     * @return array|bool
     */
    public function saveStatus($id){
        if (empty($id)) {
            return false;
        }
        try{
            $res = $this->save(array('status'=>2),array('id'=>$id));
            if ($res === false) {
                return msg(-1,'',$this->getError());
            } else {
                return msg(1,url('User/index'), '删除用户成功！');
            }
        }catch (\PDOException $e) {
            return msg(-2,'',$e->getMessage());
        }
    }
}